<?php

class CategoryController extends Controller{

	private $model;//栏目模型
	private $category;//全部栏目数据
	private $cid;//栏目id
	public function __init(){
		//获取操作栏目的模型
		$this->model = K('Category');
		// $this->category = $this->model->all();//待完善		
		// $this->category = Data::tree($this->category,'cname');
		// p($this->category);//转移到模型中实现
		//得到栏目树形数据
		// $this->category = $this->model->getTreeData();
		//读缓存数据 
		$this->category = S('category');
		$this->cid = Q('cid',0,'intval');
	}	

	//栏目列表
	public function index(){

		$this->assign('category',$this->category);
		$this->display();
	}

	/*
	*	添加栏目
	*/
	public function add(){
		if(IS_POST){
			// 通过模型添加栏目数据
			if($this->model->addData()){
				$this->success('添加成功');	
			}else{
				$this->error($this->model->error);
			}
			// $this->model->addData();
		}else{
			//显示添加栏目界面
			$this->assign('category',$this->category);
			$this->display();
		}
	}

	/*
	*	编辑栏目操作
	*/
	public function edit(){
		if(IS_POST){
			//执行模型方法，保存编辑数据
			if($this->model->saveData()){
				$this->success('编辑成功');
			}else{
				$this->error($this->model->error);
			}
		}else{
			if(!isset($this->category[$this->cid])){
				$this->error('非法操作');
			}
			//获得加完 disable属性的栏目数据，用于下拉列表
			$category = $this->model->getEditData();
			//获取当前栏目的数据
			$data = $this->model->getDataByCid();
			//分配数据 
			$this->assign('category',$category);
			$this->assign('data',$data);
			$this->display();
		}
	}

	//更新缓存
	public function cache(){
		$re = $this->model->cacheData();
		if($re){
			$this->success('更新缓存成功');
		}else{
			$this->error('更新失败');
		}
	}

	//排序
	public function sort(){
		foreach ($_POST['cid'] as $k => $v) {
			//1, $this->model->where(array('cid'=>$v))->save(array('sort'=>$_POST['sort'][$k]));
			//2,
			$data = array(
				'cid'=>$v,
				'sort'=>$_POST['sort'][$k]
				);
			$this->model->save($data);
		}
		$this->model->cacheData();
		$this->success('排序成功');
	}

}

?>